<template>
  <div class="single-container">
    <el-card class="box-card">
       <el-form 
          :model="form"
          ref="formRef"
          label-width="80px"
          :rules="formRules">
          <el-row>
              <el-col :span="8">
                <!-- 年级 -->
                <el-form-item label="年级" prop="gradeLevel"> 
                  <el-select v-model="form.gradeLevel" style="width:100%" @change="changeLevel">
                        <el-option
                          v-for="item in options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                  <!-- 学科名称 -->
                  <el-form-item label="学科" prop="subjectId">
                      <el-select v-model="form.subjectId" style="width:100%" @change="changeSubject">
                          <el-option
                            v-for="item in subjectList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id+''">
                          </el-option>
                        </el-select>
                  </el-form-item>
              </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="题干" prop="title" required>
                 <el-input v-model="form.title" @focus="inputClick(form,'title')"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="选项" required>
                <el-form-item style="width:100%;" :label="item.prefix" :key="item.prefix"  v-for="(item,index) in form.items"  label-width="50px" class="question-item-label">
                  <el-input v-model="item.prefix"  style="width:50px;margin-right:10px;"  class="question-item-content-input"/>
                  <el-input v-model="item.content" @focus="inputClick(item,'content')" style="width:400px;margin-right:10px;" />
                  <el-button type="danger" size="mini" class="deleteBtn" @click="questionItemRemove(index)">删除</el-button>
                </el-form-item>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="正确选项" prop="correctArray" required label-width="120px">
                <el-checkbox-group v-model="form.correctArray">
                  <el-checkbox v-for="item in form.items" :label="item.prefix" :key="item.prefix">{{item.prefix}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="解析" prop="analyze" required>
                <el-input v-model="form.analyze" @focus="inputClick(form,'analyze')" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="分数" prop="score" required>
                <el-input-number v-model="form.score" :precision="1" :step="1" :max="100" style="width:300px"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="难度" required>
                <el-rate v-model="form.difficult" class="question-item-rate"></el-rate>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
               <el-form-item label="知识点">
                <el-input v-model="knowledge" @focus="selectKnowledge"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item>
                <div class="btns">
                  <template v-if="form.id === null">
                    <el-button type="success" class="btn" @click="add">提交</el-button>
                  </template>
                  <template v-else>
                    <el-button type="success" class="btn" @click="update">更新</el-button>
                  </template>
                  <el-button type="primary" class="btn" @click="questionItemAdd">添加选项</el-button>
                  <el-button type="primary" class="btn" @click="showQuestion">预览</el-button>
                  <el-button type="danger" class="btn" @click="resetForm">重置</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
       </el-form>
    </el-card>
    <el-dialog  :visible.sync="richEditor.dialogVisible"  append-to-body :close-on-click-modal="false" style="width: 100%;height: 100%"   :show-close="false" center>
      <quill-editor ref="myQuillEditor" v-model="quillContent"></quill-editor>
      
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editorConfirm">确 定</el-button>
        <el-button @click="richEditor.dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
        title="选择知识点"
        :visible.sync="tree.dialogVisible"
        :modal-append-to-body="false"
        width="60%">
        <!--知识点列表-->
        <el-tree
          :data="knowledgeList"
          show-checkbox
          node-key="id"
          ref="tree"
          @check-change="handleCheckChange"
          :default-expanded-keys="[1]"
          :default-checked-keys="defaultCheckedKeys"
          :props="defaultProps">
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button class="saveBtn" type="primary" @click="confirmKnowledge">确定</el-button>
        </span>
    </el-dialog>
    <el-dialog 
        title="预览题目信息"
        :visible.sync="questionShow.dialog" 
        :modal-append-to-body="false"
        width="60%">
        <QuestionShow :qType="questionShow.qType" :question="questionShow.question" :qLoading="questionShow.loading"/>
      </el-dialog>
  </div>
</template>

<script>
import QuestionShow from './component/question';
export default {
   components: {
    QuestionShow
  },
  data(){
    return {
      //提交表单
      form: {
        id: null,
        questionType: 2,
        gradeLevel: null,
        subjectId: null,
        title: '',
        items: [
          { id: null, prefix: 'A', content: '' },
          { id: null, prefix: 'B', content: '' },
          { id: null, prefix: 'C', content: '' },
          { id: null, prefix: 'D', content: '' }
        ],
        analyze: '',
        correct: '',
        correctArray: [],
        score: '',
        difficult: 0,
        knowledgeIdList:[]
      },
      //验证规则
      formRules:{
        gradeLevel: [
          { required: true, message: '请选择年级', trigger: 'change' }
        ],
        subjectId: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        analyze: [
          { required: true, message: '请输入解析', trigger: 'blur' }
        ],
        score: [
          { required: true, message: '请输入分数', trigger: 'blur' }
        ],
        correctArray: [
          { required: true, message: '请选择正确答案', trigger: 'change' }
        ]
      },
      //年级选择
      options: [{
          value: '1',
          label: '一年级'
        }, {
          value: '2',
          label: '二年级'
        }, {
          value: '3',
          label: '三年级'
        }, {
          value: '4',
          label: '四年级'
        }, {
          value: '5',
          label: '五年级'
        }, {
          value: '6',
          label: '六年级'
        }, {
          value: '7',
          label: '初一'
        }, {
          value: '8',
          label: '初二'
        }, {
          value: '9',
          label: '初三'
        }, {
          value: '10',
          label: '高一'
        }, {
          value: '11',
          label: '高二'
        }, {
          value: '12',
          label: '高三'
        }],
        subjectList: [], //学科列表
        knowledgeList:[] , //知识点树
        richEditor: {
          dialogVisible: false,
          object: null,
          parameterName: '',
          instance: null
        },
        quillContent:"",
        tree:{
          dialogVisible: false
        },
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        //默认选中
        defaultCheckedKeys:[],
        knowledge:"",
         //题目预览
        questionShow: {
          qType: 0,
          dialog: false,
          question: null,
          loading: false
        }
        
    }
  },
  created(){
    //题目id
    
    if( this.topicId != null && this.topicId != "" ){
      this.getTopicById(this.topicId);
    }
  },
  computed:{
    topicId(){
      return this.$store.state.topicId ;
    }
  },
  mounted() {
  },
  methods:{
    getTopicById(id){
      this.getRequest("/api/admin/question/select/"+id).then(re => {
        if( re && re.code ==200){
           this.changeLevel( re.obj.gradeLevel );
           this.changeSubject(re.obj.subjectId);
            re.obj.gradeLevel = re.obj.gradeLevel + '';
            re.obj.subjectId = re.obj.subjectId +'';
            this.defaultCheckedKeys = re.obj.knowledgeIdList;
            this.knowledge = re.obj.knowledgeIdList!==null?re.obj.knowledgeIdList.toString():"";
            this.form = re.obj;
            
        }
      })
    },
     //树控件
    handleCheckChange(data, checked, indeterminate){
       let res = this.$refs.tree.getCheckedKeys();
       this.defaultCheckedKeys = res;
       this.form.knowledgeIdList = res;
     
    },
    //保存知识点信息
    confirmKnowledge(){
      this.knowledge = this.defaultCheckedKeys.toString();
      this.tree.dialogVisible=false;
    },

    selectKnowledge(){
      // console.log(1)
      this.tree.dialogVisible = true;
    },
    //切换班级时
    changeLevel(value){
      this.getRequest("/api/admin/subject/listBylevel",{
        level: value
      }).then( resp => {
        if(resp && resp.code == 200){
          this.subjectList = resp.obj;
        }
      })
    },
    //切换学科
    changeSubject(value){
      this.getRequest("/api/admin/knowledge/select/"+value).then(resp=>{
        if(resp.code == 200){
          this.knowledgeList = resp.obj;
        }
      })
    },
    //添加选项
    questionItemAdd(){
      let items = this.form.items
      let newLastPrefix
      if (items.length > 0) {
        let last = items[items.length - 1]
        newLastPrefix = String.fromCharCode(last.prefix.charCodeAt() + 1)
      } else {
        newLastPrefix = 'A'
      }
      items.push({ id: null, prefix: newLastPrefix, content: '' })
    },
    //删除选项
    questionItemRemove(index){
       this.form.items.splice(index, 1)
    },
    //重置表单
    resetForm(){
      let lastId = this.form.id
      this.$refs.formRef.resetFields()
      this.form = {
        id: null,
        questionType: 2,
        gradeLevel: null,
        subjectId: null,
        title: '',
        items: [
          { id: null, prefix: 'A', content: '' },
          { id: null, prefix: 'B', content: '' },
          { id: null, prefix: 'C', content: '' },
          { id: null, prefix: 'D', content: '' }
        ],
        analyze: '',
        correct: '',
        correctArray: [],
        score: '',
        difficult: 0
      }
    },
    //打开富文本编辑器
    inputClick (object, parameterName) {
      this.richEditor.object = object
      this.richEditor.parameterName = parameterName
      this.richEditor.dialogVisible = true

    },
    editorConfirm(){
      let content = this.quillContent;
      this.richEditor.object[this.richEditor.parameterName] = content;
      this.richEditor.dialogVisible = false;
      this.quillContent="";
      console.log(this.form);
    },
    add(){
      console.log(this.form);
      this.$refs.formRef.validate( valid => {
        if(!valid){
          this.$message.error("请输入所有的必填项");
          return false;
        }else{
          this.postRequest("/api/admin/question/edit",this.form).then(resp =>{
            if(resp && resp.code == 200){
          
              this.$router.replace("/admin/question/list");
            }
          })
        }
      })
    },
    //图片预览
    showQuestion () {
      console.log(1);
      this.questionShow.dialog = true
      this.questionShow.qType = this.form.questionType
      this.questionShow.question = this.form
    },
    update(){
      this.$refs.formRef.validate(valid => {
        if(!valid){
          this.$message.error("请输入所有必填字段");
          return false;
        }else{
          this.putRequest("/api/admin/question/edit",this.form).then(resp=>{
            if(resp && resp.code == 200){
              this.$store.commit("initTopicId","");
              this.$router.replace("/admin/question/list");
            }
          })
        }
      })
    }
  }
    
}
</script>

<style lang="scss" scoped>
.single-container{
  .box-card{
    border-radius: 10px;
    font-family: "华文楷体";
    font-size: 16px;
    .el-col{
      padding: 0 10px;
    }
    /deep/.el-form-item {
      display: flex;
      flex-direction: column;
      margin-bottom: 10px !important;
      /deep/.el-form-item {
        display: flex;
        flex-direction: row;
        margin-bottom: 10px !important;
      }
    }
    .deleteBtn{
      border: none;
      background: none;
      color:#F56C6C;
    }
    .btns{
      display: flex;
      justify-content: flex-end;
      margin: 20px 0 10px 0 ;
      .btn{
        padding-left:  35px;
        padding-right:  35px;
        font-size: 14px;
        font-family: "华文楷体";
      }
    }
  }
  .saveBtn{
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #66BB6A;
    margin-bottom: 20px;
    font-family: "华文楷体";

  }
  /deep/.el-form-item__label{
    text-align: left;
  }
  /* 选中后的字体颜色 */
  /deep/.el-radio__input.is-checked + .el-radio__label {
    color: #66BB6A !important;
  }
  /* 选中后小圆点的颜色 */
  /deep/.el-radio__input.is-checked .el-radio__inner {
    background: #66BB6A !important;
    border-color: #66BB6A !important;
  }
}
</style>